package com.zbb.online_exam.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zbb.online_exam.bean.JwtOperation;
import com.zbb.online_exam.dto.UserDto;
import com.zbb.online_exam.entity.Exam;
import com.zbb.online_exam.entity.Menu;
import com.zbb.online_exam.entity.Role;
import com.zbb.online_exam.entity.UserRole;
import com.zbb.online_exam.exception.ExamException;
import com.zbb.online_exam.mapper.MenuMapper;
import com.zbb.online_exam.mapper.RoleMapper;
import com.zbb.online_exam.mapper.UserRoleMapper;
import com.zbb.online_exam.service.MenuService;
import com.zbb.online_exam.service.UserService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zbbstart
 * @date 2021/2/22 - 22:13
 */
@Service
@Slf4j
public class MenuServiceImpl implements MenuService {
    @Autowired
    private JwtOperation jwtOperation;
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    /**
     * 获取每个菜单的名称
     */
    @Override
    public List<Menu> getMenuInfo(String token) {
        //获取Claims
        Claims claims = jwtOperation.parseJwt(token);
        //获取用户信息
        UserDto user = JSON.parseObject(String.valueOf(claims.get("user")), UserDto.class);
        //获取该用户的权限列表
        List<UserRole> userRoles = userRoleMapper.selectList(new QueryWrapper<UserRole>().eq("user_id", user.getUserId()));
        log.info("该用户拥有的所有权限id列表:"+ Arrays.toString(userRoles.toArray()));
        if (CollectionUtils.isEmpty(userRoles)){
            throw new ExamException("无任何页面权限...");
        }
        //获取菜单的列表
        List<Integer> menuIds = userRoles.stream().map(UserRole::getRoleId).filter(i -> i > 3).collect(Collectors.toList());
        log.info("菜单列表:"+menuIds);
        return menuMapper.selectBatchIds(menuIds);
    }
}
